<template>
  <LoadingGroup :error="error" :pending="pending">
    <section v-if="data.isbuy && ((data.type !== 'media' && type === 'course') || type === 'live')" class="py-4">
      <ClientOnly>
        <template #fallback>
          <LoadingSkeleton/>
        </template>
        <PlayerAudio v-if="data.type === 'audio'" :cover="data.cover" :title="data.title" :url="data.content  "/>

        <PlayerVideo v-else-if="data.type === 'video'" :url="data.content"/>

        <PlayerVideo v-else-if="type === 'live'" :url="data.playUrl"/>

      </ClientOnly>
    </section>

    <section v-else class="detail-top">

      <n-image :class="{ 'book-image' : type === 'book' }" :src="data.cover" class="image" object-fit="cover"/>

      <div class="info">
        <div class="flex flex-col items-start">
          <div class="flex items-center">
            <span class="text-xl mr-2">{{ data.title }}</span>
            <FavaBtn :goods_id="data.id" :isfave="data.isfava" :type="type"/>
          </div>
          <p class="my-2 text-xs  text-gray-400">{{ subTitle }}</p>

          <template v-if="!data.isbuy">
            <DetailActiveBar v-if="data.group || data.flashsale" :data="data"/>
            <template v-else>
              <div>
                <Price :value="data.price" class="text-xl"/>
                <Price :through="true" :value="data.t_price" class="ml-1 text-xs"/>
              </div>
              <!-- 领取优惠卷 -->
              <CouponModal v-if="type !== 'live'"/>
              <LiveStatusBar v-else :end="data.end_time" :start="data.start_time"/>
            </template>
          </template>
        </div>

        <div v-if="!data.isbuy" class="mt-auto">
          <template v-if="type === 'book'">
            <template v-if="menus.length > 0">
              <n-button :loading="loading" type="primary" @click="buy">立即学习</n-button>
              <n-button v-if="freeId" class="ml-2 " secondary strong type="primary" @click="learn({id: freeId})">
                免费试看
              </n-button>
            </template>
            <n-button v-else :disabled="true" type="primary">敬请期待</n-button>
          </template>

          <n-button v-else :loading="loading" type="primary" @click="buy">{{ btn }}</n-button>

        </div>

      </div>
    </section>

    <n-grid :x-gap="20">
      <n-grid-item :span="18">

        <DetailGroupWorks v-if="!data.isbuy && data.group" :group_id="data.group.id " />

        <section class="detail-bottom">
          <UiTab class="border-b">
            <UiTabItem v-for="(item,index) in tabs" :key="index" :active="tab === item.value"
                       @click="changeTab(item.value)">{{
                item.label
              }}
            </UiTabItem>
          </UiTab>

          <div v-if="tab === 'content'" class="content"
               v-html="(data.type === 'media' &&  data.isbuy) ? data.content : data.try"/>

          <DetailMenu v-else>
            <DetailMenuItem v-for="(item,index) in menus" :key="index" :index="index"
                            :item="item" @click="learn(item)"/>

            <Empty v-if="menus.length === 0" desc="暂无目录"/>
          </DetailMenu>
        </section>
      </n-grid-item>
      <n-grid-item :span="6">
        <HotCourseList/>
      </n-grid-item>
    </n-grid>
  </LoadingGroup>
</template>
<script setup>
// naive-ui UI
import {createDiscreteApi, NButton, NGrid, NGridItem, NImage,} from "naive-ui"

// 路由实例
const route = useRoute();

// 结构参数
const {id, type} = route.params;

useInitHead();

// 计算是否有目录
const {tabs, tab, changeTab} = useInitDetailTabs(type)

// 获取请求参数
const query = useRequestQuery()

// 接口
const {data, error, pending, refresh} = await useReadDetailApi(type, query);

// 标题
const title = computed(() => !pending.value ? data.value?.title : '详情页');

// 更换标题
useHead({title});

const o = {
  media: "图文",
  video: "视频",
  audio: "音频"
}

// 计算属性
const subTitle = computed(() => {
  let pre = "";
  if (type === "course") {
    pre = `【${o[data.value.type]}】`
  }
  return `${pre}${data.value.sub_count}人学过`
})


const btn = computed(() => {
  if (data.value.group) {
    return `立即评团`
  } else if (data.value.flashsale) {
    return `立即秒杀`
  } else {
    return `立即学习`
  }
})


// 购买学习事件
const loading = ref(false);
const buy = () => {
  useHashAuth(async () => {
    // 免费学习
    if (Number(data.value.price) === 0) {

      loading.value = true;
      const {error: learnError} = await useLearnApi({
        goods_id: data.value.id,
        type,
      })

      loading.value = false;

      if (!learnError.value) refresh()
    }


    // 评团
    console.log(data.value.group)
    if (data.value.group) {
      const t = {
        group_id: data.value.group.id,
      }
      useCreateOrderApi(t, 'group').then((res) => {
        if (!res.error.value) {
          console.log(res)
          navigateTo(`/pay?no=${res.data.value.no}`)
        }
      })

      return

    }


    // 付费学习
    let ty = 'course';
    let id = data.value.id;
    console.log(type);
    if (type === 'book') {
      ty = 'book'
    } else if (type === 'live') {
      ty = 'live'
    } else if (type === 'column') {
      ty = 'column'
    }

    if (data.value.flashsale) {
      ty = 'flashsale';
      id = data.value.flashsale.id;
    }

    navigateTo(`/createorder?id=${id}&type=${ty}`);


  })

}

// 菜单
const menus = computed(() => (type === 'book' ? data.value.book_details : data.value.column_courses) || [])

// 点击菜单
const learn = (item) => {
  console.log(item);
  useHashAuth(() => {
    const {message} = createDiscreteApi(['message']);

    // 专栏
    if (type === "column" && Number(item.price) !== 0 && !data.value.isbuy) {
      return message.error("请先购买该专栏");
    }

    // 跳转
    let url = "";
    if (type === "column") {
      url = `/detail/course/${item.id}?column_id=${data.value.id}`;
    } else if (type === 'book') {
      url = `/book/${data.value.id}/${item.id}`
    }
    navigateTo(url);
  })
}

// 电子书第一免费章节
const freeId = computed(() => {
  let fid = 0;
  if (type === 'book' && data.value) {
    let item = data.value.book_details.find((o) => Number(o.isfree) === 1);

    if (item) {
      fid = item.id;
    }
  }
  return fid;
})

// 获取query
function useRequestQuery() {
  const {column_id, group_id, flashsale_id} = route.query;
  let query = {
    id
  }
  if (column_id) {
    query.column_id = column_id;
  }

  if (group_id) {
    query.group_id = group_id;
  } else if (flashsale_id) {
    query.flashsale_id = flashsale_id;
  }
  return query
}


// 初始化Tab
function useInitDetailTabs(t) {
  const tabs = computed(() => {
    let ts = [
      {
        label: "详情",
        value: "content",
      }
    ];

    if (t === "column" || t === "book") {
      ts.push({label: "目录", value: "menu"})
    }
    return ts
  })

  const tab = ref("content");

  const changeTab = (e) => {
    tab.value = e;
  }

  return {tabs, tab, changeTab};
}


// 初始化
function useInitHead() {
  if (type === "course") {
    useHead({
      link: [
        {
          rel: "stylesheet",
          href: "/aplayer/APlayer.min.css"
        }
      ],
      script: [
        {
          src: "/aplayer/APlayer.min.js"
        },
        {
          src: "//unpkg.byted-static.com/xgplayer/2.31.2/browser/index.js"
        }
      ]
    })
  }

  if (type === "live") {
    useHead({
      link: [
        {
          rel: "stylesheet",
          href: "https://unpkg.byted-static.com/xgplayer/3.0.10/dist/index.min.css"
        }
      ],
      script: [
        {
          src: "//unpkg.byted-static.com/xgplayer/3.0.10/dist/index.min.js",
        },
        {
          src: "//unpkg.byted-static.com/xgplayer-flv.js/3.0.0-alpha.1/dist/index.min.js"
        }
      ]
    })
  }
}
</script>

<style lang="css" scoped>
.detail-top {
  @apply rounded bg-white flex p-5 my-5;
}

.detail-top .image {
  @apply rounded w-[340px] h-[200px] mr-5;
}

.detail-top .book-image {
  @apply rounded w-[130px] h-[180px] mr-8 ml-3
}

.detail-top .info {
  @apply flex-1 flex flex-col py-2;
}

.detail-bottom {
  @apply bg-white rounded mb-5;
}

.detail-bottom .content {
  @apply px-5 pb-5;
}

.detail-bottom .content img {
  max-width: 100%;
}
</style>
